﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using FreeImageAPI;

namespace Imagenator.Controls
{
	partial class IcoSaveControl : SaveControl
	{
		protected IcoSizes[] IconSizes { get; private set; }

		public IcoSaveControl()
			:base()
		{
			InitializeComponent();
		}

		protected override void OnLoad(EventArgs e)
		{
			Settings settings = Settings.Load();
			this.lbIcoSizes.SelectedFlags = settings.IconSizes;
			base.OnLoad(e);
		}

		public override void Close()
		{
			Settings settings = Settings.Load();
			settings.IconSizes = this.lbIcoSizes.SelectedFlags;
			base.Close();
		}

		public override bool BeginSaving()
		{
			if (base.BeginSaving() == false)
				return false;
			IcoSizes[] sizes = this.lbIcoSizes.GetSelectedFlags();
			if (sizes.Length < 1)
			{
				ArgusLib.Controls.MessageBox.Show(Localization.Text.MBSelectIconSizeText, Localization.Text.MBSelectIoncSizeCaption);
				return false;
			}
			Array.Sort(sizes, new Comparison<IcoSizes>((s1, s2) =>
				{
					return (int)(s2.ToUInt64() - s1.ToUInt64());
				}));
			this.IconSizes = sizes;
			return true;
		}

		protected override bool ModifyImage(FreeImageBitmap image, ArgusLib.Controls.ProgressBox.ThreadState threadState)
		{
			bool converted = this.ConvertImageType(image, threadState);
			bool resized = this.ResizeImage(image, threadState);
			return converted || resized;
		}

		protected override bool ResizeImage(FreeImageBitmap image, ArgusLib.Controls.ProgressBox.ThreadState threadState)
		{
			RGBQUAD color = new RGBQUAD(Color.Transparent);
			if (image.Width > image.Height)
			{
				int a = (image.Width - image.Height) / 2;
				image.EnlargeCanvas<RGBQUAD>(0, a, 0, a, color, FREE_IMAGE_COLOR_OPTIONS.FICO_RGBA);
			}
			else if (image.Height > image.Width)
			{
				int a = (image.Width - image.Height) / 2;
				image.EnlargeCanvas<RGBQUAD>(a, 0, a, 0, color, FREE_IMAGE_COLOR_OPTIONS.FICO_RGBA);
			}

			int s = (int)this.IconSizes[0] << 4;
			image.Rescale(s, s, this.ResizeFilter);
			return true;
		}

		public override void SaveImage(FreeImageBitmap image, FileInfo srcFile, FileInfo dest, ArgusLib.Controls.ProgressBox.ThreadState threadState)
		{
			srcFile = null;
			base.SaveImage(image, srcFile, dest, threadState);
			for (int i = 1; i < this.IconSizes.Length; i++)
			{
				int s = (int)this.IconSizes[i] << 4;
				image.Rescale(s, s, this.ResizeFilter);
				image.SaveAdd();
			}
		}
	}
}
